package processor

import (
	"fmt"
	"game/src/common"
	"game/src/logic"
	"strconv"
	"strings"
)

func (p *HeartBeatRouter) PreHandle(request common.IRequest) bool {
	//request.GetConnection().SendBuffMsg(99, []byte(time.Now()))
	return false
}

func (p *LoginRouter) PreHandle(request common.IRequest) bool {
	name := string(request.GetData())
	roleOld, _ := logic.GameServer.GetOnlineMgr().Get(name)
	if roleOld != nil {
		err := request.GetConnection().SendBuffMsg(0, []byte("用户已在线!!"))
		if err != nil {
			fmt.Println(roleOld.Data.Name, "登录时出错：", err)
		}
		return false
	}
	roleData, err := logic.Ds.GetRoleByName(name)
	if err != nil {
		roleData = logic.NewRoleData(name)
		logic.Ds.SaveRole(roleData)
	}

	role := logic.NewRole(roleData)
	if role.Data.AllianceName != "" {
		allianceByName := logic.Ds.GetAllianceByName(role.Data.AllianceName)
		role.Alliance = allianceByName
	}
	role.Connection = request.GetConnection()
	logic.GameServer.GetOnlineMgr().Add(role)
	msg := "登录成功:" + role.Data.Name
	if role.Data.AllianceName != "" {
		msg += ", 公会 ：" + role.Alliance.AllianceName
	}
	request.GetConnection().SetProperty("role", &role)
	request.GetConnection().SendBuffMsg(0, []byte(msg))
	return true
}

func (p *CreatAliRouter) Handle(request common.IRequest) {
	params := strings.Fields(string(request.GetData()))
	if len(params) != 2 {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：创建公会时参数数量不对！！！"))
		return
	}
	newName := params[1]
	aOld := logic.Ds.GetAllianceByName(newName)
	if aOld != nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：公会已存在，换个名吧！！！"))
		return
	}
	alliance := logic.NewAllianceData(newName)
	i, _ := request.GetConnection().GetProperty("role")
	r := i.(**logic.Role)
	role := *r
	if role.Data.AllianceName != "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：已经有公会了！！"))
		return
	}
	alliance.Init()
	alliance.ChairmanName = role.Data.Name
	logic.JoinAlliance(alliance, role, "Chairman")
	role.Data.AllianceName = alliance.AllianceName
	role.Alliance = alliance
	logic.Ds.SaveAlliance(alliance)
	role.Alliance = alliance
	request.GetConnection().SendBuffMsg(0, []byte("创建公会成功："+alliance.AllianceName))
}

func (p *WhichAliRouter) Handle(request common.IRequest) {
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	builder := strings.Builder{}
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	alliance := role.Alliance
	builder.WriteString("以下是公会信息：\n")
	builder.WriteString("公会：" + alliance.AllianceName + "\t会长：" + alliance.ChairmanName + "\n")
	alliance.MemberMap.Range(func(k, v interface{}) bool {
		builder.WriteString("名称：" + k.(string) + ",\t职务：" + v.(*logic.AllianceMember).Job + ",\t加入时间：" + v.(*logic.AllianceMember).JoinTime.Format("2006-01-02 15:04:05") + "\t,贡献值：" + strconv.Itoa(v.(*logic.AllianceMember).Contribute) + "\n")
		return true
	})
	//for key, value := range alliance.MemberMap {
	//	builder.WriteString("名称：" + key + ",\t职务：" + value.Job + ",\t加入时间：" + value.JoinTime.Format("2006-01-02 15:04:05") + "\t,贡献值：" + strconv.Itoa(value.Contribute) + "\n")
	//}
	builder.WriteString("\n仓库信息：\n")
	for key, value := range alliance.Capacity {
		if key%5 == 0 {
			builder.WriteString("\n")
		} else {
			builder.WriteString("\t")
		}

		str := "位" + strconv.Itoa(key) + ":"
		if value != nil {
			str += value.Name + "*" + strconv.Itoa(int(value.Num))
		} else {
			str += "无"
		}
		builder.WriteString(fmt.Sprintf("%-10s", str))
	}
	builder.WriteString("\n")
	request.GetConnection().SendBuffMsg(0, []byte(builder.String()))
}

func (p *AllAliRouter) Handle(request common.IRequest) {
	builder := strings.Builder{}
	builder.WriteString("以下是所有的公会：\n")
	for key, value := range logic.Ds.GetAllianceByList() {
		builder.WriteString("公会名称：" + key + "\t" + ", 会长：" + value.ChairmanName + "\t" + ", 人数：" + strconv.Itoa(int(value.MemberSize())) + "\n")
	}
	builder.WriteString("\n")
	request.GetConnection().SendBuffMsg(0, []byte(builder.String()))
}

func (p *JoinAliRouter) Handle(request common.IRequest) {
	params := strings.Fields(string(request.GetData()))
	if len(params) != 2 {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：加入公会时参数数量不对！！！"))
		return
	}
	newName := params[1]
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName != "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：已经有公会了！！"))
		return
	}
	alliance := logic.Ds.GetAllianceByName(newName)
	if alliance == nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：公会不存在！！！"+newName))
		return
	}
	logic.JoinAlliance(alliance, role, "normal")
	role.Data.AllianceName = alliance.AllianceName
	role.Alliance = alliance
	request.GetConnection().SendBuffMsg(0, []byte("加入成功"))
}

func (p *DismissAliRouter) Handle(request common.IRequest) {
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	if role.Data.Name != role.Alliance.ChairmanName {
		request.GetConnection().SendBuffMsg(0, []byte("ERR:操作失败，只有会长可以解散"))
		return
	}
	role.Alliance.Dismiss()
	request.GetConnection().SendBuffMsg(0, []byte("解散成功"))
}

func (p *IncreaseCapacityRouter) Handle(request common.IRequest) {
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	if role.Data.Name != role.Alliance.ChairmanName {
		request.GetConnection().SendBuffMsg(0, []byte("ERR:操作失败，只有会长可以扩容"))
		return
	}
	if role.Alliance.ExpendTimes >= 1 {
		request.GetConnection().SendBuffMsg(0, []byte("ERR:操作失败，扩容次数达到上线"))
		return
	}
	role.Alliance.ExpandCapacity()
	request.GetConnection().SendBuffMsg(0, []byte("扩充成功"))
}

func (p *StoreCapacityRouter) Handle(request common.IRequest) {
	params := strings.Fields(string(request.GetData()))
	if len(params) != 4 {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：放置道具时参数数量不对！！！"))
		return
	}
	itemId64, err := strconv.ParseInt(params[1], 10, 32)
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：放置道具时道具id不对！！！"))
		return
	}
	itemId32 := int32(itemId64)
	itemNum64, err := strconv.ParseInt(params[2], 10, 32)
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：放置道具时道具数量不对！！！"))
		return
	}
	itemNum32 := int32(itemNum64)
	index, err := strconv.Atoi(params[3])
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：放置道具时下标值不对！！！"))
		return
	}
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	err = role.Alliance.StoreItemIndex(itemId32, itemNum32, index)
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte(err.Error()))
	} else {
		request.GetConnection().SendBuffMsg(0, []byte("放入成功"))
	}

}

func (p *DestroyItemCapacityRouter) Handle(request common.IRequest) {
	params := strings.Fields(string(request.GetData()))
	if len(params) != 2 {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：销毁道具时参数数量不对！！！"))
		return
	}
	index, err := strconv.Atoi(params[1])
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：销毁道具时下标值不对！！！"))
		return
	}
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	if role.Data.Name != role.Alliance.ChairmanName {
		request.GetConnection().SendBuffMsg(0, []byte("ERR:操作失败，只有会长可以销毁"))
		return
	}

	err = role.Alliance.DeleteItemIndex(index)
	if err != nil {
		request.GetConnection().SendBuffMsg(0, []byte(err.Error()))
		return
	}

	request.GetConnection().SendBuffMsg(0, []byte("清理成功"))
}

func (p *ClearUpCapacityRouter) Handle(request common.IRequest) {
	i, _ := request.GetConnection().GetProperty("role")
	role := *i.(**logic.Role)
	if role.Data.AllianceName == "" {
		request.GetConnection().SendBuffMsg(0, []byte("ERR：还没有公会！！"))
		return
	}
	if role.Data.Name != role.Alliance.ChairmanName {
		request.GetConnection().SendBuffMsg(0, []byte("ERR:操作失败，只有会长可以整理"))
		return
	}
	role.Alliance.CleanUpItem()
	request.GetConnection().SendBuffMsg(0, []byte("整理完成"))
}
